package Test.StreamUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 序列化工具类
 * @author dell
 *
 */
public class StreamUtils {

    /**
     * 序列化,List
     */
    public static <T> boolean writeObject(List<T> list,File file)
    {
        T[] array = (T[]) list.toArray();
        
        
        try(ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file))) 
        {
            out.writeObject(array);
            out.flush();
            return true;
        }
        catch (IOException e) 
        {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 反序列化,List
     */
    public static <E> List<E> readObjectForList(File file)
    {
        E[] object;
        
        try(ObjectInputStream out = new ObjectInputStream(new FileInputStream(file)))
        {
            object = (E[]) out.readObject();
            return  new ArrayList(Arrays.asList(object)) ;
        }
        catch (IOException e) 
        {
            e.printStackTrace();
        } 
        catch (ClassNotFoundException e) 
        {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 序列化 map
     * @param <K>
     * @param <V>
     * @param map
     * @param file
     * @return
     */
    public static <K,V> boolean writeObject(Map<K,V> map,File file)
    {
    	List<Map.Entry<K, V>> list = new ArrayList<>(map.entrySet());
    	
    	@SuppressWarnings("unchecked")
		Map.Entry<K, V>[] array =  (Entry<K, V>[]) list.toArray();
        
        
        try(ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file))) 
        {
            out.writeObject(array);
            out.flush();
            return true;
        }
        catch (IOException e) 
        {
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * 反序列化,Map
     */
    public static <K,V> Map<K,V> readObjectForMap(File file)
    {
    	Entry<K, V>[] object;
        
        try(ObjectInputStream out = new ObjectInputStream(new FileInputStream(file)))
        {
            object = (Entry<K, V>[]) out.readObject();
            HashMap<K, V> map = new HashMap<K, V>();
            for(int i =0;i<object.length;i++) {
            	map.put(object[i].getKey(), object[i].getValue());
            }
            
            return map;
        }
        catch (IOException e) 
        {
            e.printStackTrace();
        } 
        catch (ClassNotFoundException e) 
        {
            e.printStackTrace();
        }
        return null;
    }
}
